<template>
    <div id="data-source">
        <el-row class="search-bar">
            <el-col :span="4">
                <el-input v-model="searchParams.codeOrName" placeholder="请输入数据源ID或名称" size="mini"></el-input>
            </el-col>
            <el-col :span="8" style="padding: 0 10px">
                <el-button size="mini" type="primary" @click="handleBtn('search')">查询</el-button>
                <el-button size="mini" type="primary" @click="handleBtn('add')">新增</el-button>
                <el-button size="mini" type="danger" @click="handleBtn('deletes')">删除</el-button>
            </el-col>

            <el-col :span="5" :offset="7" style="text-align: right">
                <el-button size="mini" type="primary" @click="layoutDialog = true">布局设置</el-button>
            </el-col>
        </el-row>

        <RiskTableP
            ref="risk-table"
            :tableConfig="tableConfig"
            :tableData="tableData"
            :column="showColumns"
            :paging="paging"
            :searchParams="searchParams"
            v-loading="tableLoading"
            @page-change="getTableData"
            :key="tableKey"
            style="height: calc(100% - 70px)"
        >
            <template #operation="{ row }">
                <RiskIconButton type="primary" icon="el-icon-view" topTitle="查看" @on-click="handleBtn('look', row)"></RiskIconButton>
                <RiskIconButton type="primary" icon="el-icon-edit" topTitle="编辑" @on-click="handleBtn('edit', row)"></RiskIconButton>
                <RiskIconButton type="danger" icon="el-icon-delete" topTitle="删除" @on-click="handleBtn('delete', row)"></RiskIconButton>
            </template>
        </RiskTableP>

        <!-- 布局设置 -->
        <RiskTableLayout
            ref="risk-table-layout"
            :tableName="'DATA_SOURCE'"
            :visible.sync="layoutDialog"
            :column="columns"
            :fixedColumns="fixedColumns"
        />

        <!-- 新增/查看/编辑 -->
        <SourceDialog v-if="visible" :visible.sync="visible" :type="type" :detail="detailMsg" @submit="handleSubmit" />

        <!-- 删除弹窗 -->
        <yh-dialog title="确定删除以下数据源吗？" :visible.sync="deleteVisible" width="600px" drag>
            <div>
                {{ checkedRows.map(item => item.id + '(' + item.dataSourceName + ')').join(',') }}
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="deleteVisible = false" size="mini">取 消</el-button>
                <el-button @click="handleDelete" :loading="delLoading" size="mini" type="primary">确 定 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { Component, Prop, Vue } from 'vue-property-decorator';
import { ColumnVO, PageVO, TableConfigVO, VueObject } from '@/common/vo';
import { downLoadFile } from '@/utils/request';
import RiskPagination from '@/common/components/risk-pagination.vue';
import { dateFormat, numberFormat, timeFormat } from '@/utils/tools';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import API from './api/data-source';
import { DataSourceDTO, DataSourceRepVO, DataSourceVO } from './vo/data-source';
import RiskTableLayout from '@/common/components/risk-table-layout-plus.vue';
import SourceDialog from './data-source/source-dialog.vue';

@Component({ name: 'DataSource', components: { RiskTableP, RiskEntryInput, RiskTableLayout, RiskPagination, RiskIconButton, SourceDialog } })
export default class DataSource extends Vue {
    searchParams: DataSourceDTO = {
        codeOrName: '',
        idMH: '',
        dataSourceTypeList: [],
        dataSourceName: '',
        jdbcUrl: '',
        apiUrl: '',
        monitorInfo: '',
        remark: '',
        dtCtUser: '',
        dtMdUser: '',
    };
    paging: PageVO = { currentPage: 1, pageSize: 25, total: 0 };
    tableLoading: boolean = false;
    tableConfig: TableConfigVO = {
        rowKey: 'id', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: DataSourceVO[] = [];
    columns: ColumnVO[] = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 50,
        },
        {
            title: '数据源ID',
            field: 'id',
            sortable: true,
            sortField: 'N_ID',
            filters: [{ data: '' }],
            filterField: 'idMH',
            filterType: 'search',
            minWidth: 130,
        },
        {
            title: '数据源类型',
            field: 'dataSourceType',
            sortable: true,
            sortField: 'C_DATA_SOURCE_TYPE',
            filters: [
                { label: 'MYSQL', value: 'MYSQL' },
                { label: 'ORACLE', value: 'ORACLE' },
                { label: '外部API接口', value: 'API' },
            ],
            filterField: 'dataSourceTypeList',
            align: 'center',
            minWidth: 150,
            render: (value, record) => (value === 'API' ? '外部API接口' : value),
        },
        {
            title: '数据源名称',
            field: 'dataSourceName',
            sortable: true,
            sortField: 'C_DATA_SOURCE_NAME',
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 180,
        },
        {
            title: '用户名',
            field: 'userName',
            sortable: true,
            sortField: 'C_USER_NAME',
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 120,
        },
        {
            title: '密码',
            field: 'passWord',
            minWidth: 120,
            render: (value, record) => '*** ** ***',
        },
        {
            title: '数据库连接串',
            field: 'jdbcUrl',
            sortable: true,
            sortField: 'C_JDBC_URL',
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 180,
        },
        {
            title: '接口地址',
            field: 'apiUrl',
            sortable: true,
            sortField: 'C_API_URL',
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 180,
        },
        // {
        //     title: '监控点信息',
        //     field: 'monitorInfo',
        //     sortable: true,
        //     sortField: 'C_MONITOR_INFO',
        //     filters: [{ data: '' }],
        //     filterType: 'search',
        //     minWidth: 150,
        // },
        {
            title: '备注',
            field: 'remark',
            sortable: true,
            sortField: 'C_REMARK',
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 180,
        },
        {
            title: '创建人',
            field: 'dtCtUserName',
            sortable: true,
            sortField: 'D_DT_CT_USER',
            filters: [{ data: '' }],
            filterField: 'dtCtUser',
            filterType: 'search',
            minWidth: 120,
        },
        {
            title: '创建时间',
            field: 'dtCtDate',
            align: 'center',
            sortable: true,
            sortField: 'D_DT_CT_DATE',
            minWidth: 160,
            render: (value, record) => dateFormat(value) + ' ' + timeFormat(record.dtCtTime),
        },
        {
            title: '更新人',
            field: 'dtMdUserName',
            sortable: true,
            sortField: 'D_DT_MD_USER',
            filters: [{ data: '' }],
            filterField: 'dtMdUser',
            filterType: 'search',
            minWidth: 120,
        },
        {
            title: '更新时间',
            field: 'dtMdDate',
            align: 'center',
            sortable: true,
            sortField: 'D_DT_MD_DATE',
            minWidth: 160,
            render: (value, record) => dateFormat(value) + ' ' + timeFormat(record.dtMdTime),
        },
        { title: '操作', field: 'operation', minWidth: 150, align: 'center', fixed: 'right' },
    ];
    showColumns: ColumnVO[] = [];
    fixedColumns: ColumnVO[] = [
        { title: '数据源ID', field: 'id' },
        // { title: '数据源名称', field: 'dataSourceName' },
        { title: '操作', field: 'operation' },
    ];

    layoutDialog: boolean = false;

    tableKey: number = 0;

    deleteVisible: boolean = false;

    checkRowKeys: string[] = [];
    checkedRows: any[] = [];

    delLoading: boolean = false;

    visible: boolean = false;
    type: string = ''; // look || edit || add
    detailMsg: any = {};

    async mounted() {
        // 监听布局设置
        this.$watch(
            () => {
                return (this.$refs['risk-table-layout'] as VueObject).showColumns;
            },
            val => {
                this.showColumns = val && val.length ? val : this.columns;
                this.tableKey++;
            }
        );

        this.getTableData();

        window.addEventListener('message', this.refresh);
    }

    destroyed() {
        window.removeEventListener('message', this.refresh);
    }

    refresh(event) {
        if (event.data === 'Refresh') {
            console.log('vue-Refresh!');
            window.location.reload();
        }
    }

    /**
     * 表格数据
     */
    getTableData(): void {
        this.tableLoading = true;
        API.getDataSourceList({ ...this.searchParams, paging: this.paging })
            .then((res: DataSourceRepVO) => {
                this.tableData = res?.list || [];
                this.paging.total = res?.total || 0;
                this.tableLoading = false;

                // this.tableData = [
                //     {
                //         id: '1', // 数据源id
                //         dataSourceName: '聚源', // 数据源名称
                //         userName: 'userName', // 用户名
                //         passWord: 'password', // 密码
                //         dataSourceType: '1', // 数据源类型
                //         jdbcUrl: 'JDBC连接串', // JDBC url地址
                //         apiUrl: '192.168.75.123', // 接口地址
                //         schema: '', // 方案
                //         monitorInfo: '监控信息', // 监控点信息
                //         status: '0', // 是否启动
                //         remark: '我是备注', // 备注
                //         dtCtTime: 94647, // 创建时间
                //         dtCtDate: 20230726, // 创建日期
                //         dtCtUser: '假张成', // 创建人
                //     },
                // ];
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 按钮点击事件
     */
    handleBtn(type: string, row): void {
        if (type == 'search') {
            this.paging.currentPage = 1;
            this.getTableData();
        } else if (type == 'refresh') {
            this.getTableData();
        } else if (type == 'export') {
            // const checkedKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            // const url = this.type === 'today' ? '/event/report/export' : '/event/history/report/export';
            // downLoadFile({
            //     url,
            //     method: 'post',
            //     data: checkedKeys.length ? { resultIds: checkedKeys } : this.searchParams,
            // });
            // this.$nextTick(() => {
            //     (this.$refs['risk-table'] as any).resetCheckRowKeys();
            // });
        } else if (type === 'deletes') {
            this.checkRowKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            if (this.checkRowKeys.length < 1) {
                this.yh_message_warn('请先勾选需删除的数据源!');
                return;
            }
            this.checkedRows = (this.$refs['risk-table'] as any).checkedRows; // 产品台账发版就生效

            this.deleteVisible = true;
        } else if (type === 'look') {
            this.type = type;
            this.detailMsg = row;
            this.visible = true;
        } else if (type === 'edit') {
            this.type = type;
            this.detailMsg = row;
            this.visible = true;
        } else if (type === 'delete') {
            this.checkRowKeys = [row.id];
            this.checkedRows = [{ id: row.id, dataSourceName: row.dataSourceName }];
            this.deleteVisible = true;
        } else if (type === 'add') {
            this.type = type;
            this.detailMsg = {};
            this.visible = true;
        }
    }

    /**
     * 删除事件
     */
    handleDelete(): void {
        this.delLoading = true;
        API.deleteDataSource(this.checkRowKeys)
            .then((res: any) => {
                this.yh_message_success('删除成功!');
            })
            .finally(() => {
                this.delLoading = false;
                this.deleteVisible = false;
                this.getTableData();

                this.checkRowKeys = [];
                this.$nextTick(() => {
                    (this.$refs['risk-table'] as any).resetCheckRowKeys();
                });
            });
    }

    handleSubmit(data: DataSourceDTO): void {
        if (this.type === 'add') {
            API.addDataSource(data)
                .then((res: any) => {
                    this.yh_message_success('新增成功!');
                })
                .finally(() => {
                    this.visible = false;
                    this.getTableData();
                });
        } else if (this.type === 'edit') {
            API.editDataSource(data)
                .then((res: any) => {
                    this.yh_message_success('编辑成功!');
                })
                .finally(() => {
                    this.visible = false;
                    this.getTableData();
                });
        }
    }
}
</script>
<style lang="scss" scoped>
#data-source {
    height: 100%;
    padding: 0 5px;
    overflow: hidden;

    .search-bar {
        border: 1px solid #d7d7d7;
        margin: 10px 0;
        padding: 0 5px;
        height: 50px;
        line-height: 50px;
    }
}

/***  collapse-tags样式 ***/
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
    display: flex;
    align-items: center;
    width: 100%;
    max-width: fit-content;
    padding: 0px 5px 0 0;
    margin: 4px 0px 2px 2px;
    .el-select__tags-text {
        display: inline-block;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light:first-of-type {
    width: 63%;
}
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light:last-of-type {
    width: 100%;
}
/***  collapse-tags样式 ***/
</style>
